<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useDialog, NSpace, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { DataTableRowKey, DataTableColumns } from 'naive-ui'
import http from '@/tools/http'
import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'

type RowData = {
    jobLogId?: string
    jobName?: string
    jobGroup?: string
    beanName?: string
    triggerType?: string
    startTime?: string
    duration?: string
    result?: string
    remark?: string
    creator?: string
}

const dictStore = useDictStore()
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const dialog = useDialog()

const jobLogTableColumns: DataTableColumns<RowData> = [
    {
        type: 'selection',
        width: 25
    }, {
        title: "任务名称",
        key: "jobName",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "任务分组",
        key: "jobGroup",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "执行目标",
        key: "beanName",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "调度类型",
        key: "triggerType",
        width: 70,
        ellipsis: {
            tooltip: true
        },
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("SCHEDULE_TRIGGER_TYPE", rowData.triggerType)
        }
    }, {
        title: "开始时间",
        key: "startTime",
        width: 90,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "耗时",
        key: "duration",
        width: 40,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "执行结果",
        key: "result",
        width: 70,
        ellipsis: {
            tooltip: true
        },
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("SCHEDULE_EXECUTE_RES", rowData.result)
        }
    }, {
        title: "备注",
        key: "remark",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "创建人",
        key: "creator",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作",
        key: "actions",
        width: 60,
        fixed: "right",
        ellipsis: {
            tooltip: true
        },
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    userStore.hasAuth("job-log:delete") ? h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteJobLog()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteJobLog(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除？" }
                        }
                    ) : null
                ]
            )
        }
    }
]

const jobLogData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const jobLogSearchFormValue = reactive<any>({
    pageNum: 1,
    pageSize: 10,
    jobName: "",
    jobGroup: ""
})

const checkedRowKeys = ref<DataTableRowKey[]>([])

onMounted(() => {
    jobLogSearchFormValue.jobName = route.query.jobName
    jobLogSearchFormValue.jobGroup = route.query.jobGroup
    pageJobLog()
})

const formData = reactive<RowData>({
    jobLogId: "",
    jobName: "",
    jobGroup: "",
    beanName: "",
    triggerType: "",
    startTime: "",
    duration: "",
    result: "",
    remark: "",
    creator: ""
})

function handleCheckRowKeys(rowKeys: DataTableRowKey[]) {
    console.log('aaa')
    checkedRowKeys.value = rowKeys
}

function pageNumChange(pageNum: number) {
    jobLogSearchFormValue.pageNum = pageNum
    pageJobLog()
}

function pageSizeChange(pageSize: number) {
    jobLogSearchFormValue.pageSize = pageSize
    pageJobLog()
}

function openDeleteJobLog(row: any) {
    formData.jobLogId = row.jobLogId
    formData.jobName = row.jobName
    formData.jobGroup = row.jobGroup
    formData.beanName = row.beanName
    formData.triggerType = row.triggerType
    formData.startTime = row.startTime
    formData.duration = row.duration
    formData.result = row.result
    formData.remark = row.remark
    formData.creator = row.creator
}

function pageJobLog() {
    http.post("/schedule/log/page", jobLogSearchFormValue).then(({ data }) => {
        jobLogData.pageNum = data.data.pageNum
        jobLogData.pageSize = data.data.pageSize
        jobLogData.pages = data.data.pages
        jobLogData.total = data.data.total
        jobLogData.list.length = 0
        for (let i = 0; i < data.data.list.length; i++) {
            jobLogData.list.push(data.data.list[i])
        }
    })
}

const notification = useNotification()

function batchDeleteLog() {
    dialog.create({
        title: '温馨提示',
        content: '确定删除选中的日志吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            http.post("/schedule/log/batch-delete", checkedRowKeys.value).then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '删除成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    pageJobLog()
                }
            })
        }
    })
}

function deleteJobLog() {
    http.post("/schedule/log/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageJobLog()
        }
    })
}

function clearLog() {
    dialog.create({
        title: '温馨提示',
        content: '确定清空所有日志吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            http.post("/schedule/log/clear").then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '清空成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    pageJobLog()
                }
            })
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="header" style="font-size:18px;font-weight:500;line-height:34px;">
            <n-space justify="space-between">
                <div>
                    任务执行日志
                </div>
                <div>
                    <n-button quaternary @click="router.back()">返回</n-button>
                </div>
            </n-space>
        </div>
        <div class="btn-group" style="margin-top: 0px;">
            <n-space>
                <n-button v-if="userStore.hasAuth('job-log:batch-delete')" :disabled="checkedRowKeys.length === 0"
                    attr-type="button" @click="batchDeleteLog()">批量删除</n-button>
                <n-button v-if="userStore.hasAuth('job-log:clear')" attr-type="button" @click="clearLog()">清空所有日志</n-button>
                <n-button attr-type="button" @click="pageJobLog()">刷新</n-button>
            </n-space>
        </div>
        <div class="data-table" style="top:132px">
            <n-data-table :scroll-x="415" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :row-key="row => row.jobLogId" @update:checked-row-keys="handleCheckRowKeys" :columns="jobLogTableColumns"
                :data="jobLogData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="jobLogData.pageNum" :page-size="jobLogData.pageSize"
                :item-count="jobLogData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>